package com.yy.service.impl;


import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yy.common.ErrorCode;
import com.yy.exception.BusinessException;
import com.yy.mapper.UserMapper;
import com.yy.model.entity.User;
import com.yy.model.vo.LoginUserVO;
import com.yy.service.UserService;
import com.yy.utils.ThreadLocalUtil;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import javax.servlet.http.HttpServletRequest;

import java.util.concurrent.TimeUnit;

import static com.yy.constant.UserConstant.USER_LOGIN_STATE;
import static com.yy.constant.UserConstant.USER_Seession_ID;

@Service
@RequiredArgsConstructor
@Slf4j
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {
    /**
     * 盐值，混淆密码
     */
    public static final String SALT = "yupi";

    private final RedisTemplate<String, Object> redisTemplate;

    @Override
    public LoginUserVO userLogin(String userAccount, String userPassword, HttpServletRequest request) {
        // 1. 校验
        if (StringUtils.isAnyBlank(userAccount, userPassword)) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "参数为空");
        }
        if (userAccount.length() < 4) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "账号错误");
        }
        if (userPassword.length() < 8) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "密码错误");
        }
        // 2. 加密
        String encryptPassword = DigestUtils.md5DigestAsHex((SALT + userPassword).getBytes());
        // 查询用户是否存在
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("userAccount", userAccount);
        queryWrapper.eq("userPassword", encryptPassword);
        User user = this.baseMapper.selectOne(queryWrapper);
        // 用户不存在
        if (user == null) {
            log.info("user login failed, userAccount cannot match userPassword");
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "用户不存在或密码错误");
        }
        //todo  3. 记录用户的登录态  到redis
//        request.getSession().setAttribute(USER_LOGIN_STATE, user);
        String sessionId = request.getSession().getId();
        redisTemplate.opsForValue().set(USER_LOGIN_STATE + sessionId, JSONUtil.parse(user).toString(), 1200, TimeUnit.SECONDS);
        LoginUserVO loginUserVO = this.getLoginUserVO(user);
        loginUserVO.setSessionId(sessionId);
        return loginUserVO;
    }


    /**
     * 获取当前登录用户
     *
     * @param request
     * @return
     */
    @Override
    public LoginUserVO getLoginUser(HttpServletRequest request) {
        //todo 1. 更改策略
        // 先判断是否已登录
        LoginUserVO loginUserVO = (LoginUserVO) ThreadLocalUtil.getAttribute();
        if (loginUserVO != null) {
            //在redis查
            // 从redis中获取用户信息
            String sessionId = loginUserVO.getSessionId();

            if (sessionId != null) {
                String jsonStr = (String) redisTemplate.opsForValue().get(USER_LOGIN_STATE + sessionId);
                try {
                    User currentUser = JSONUtil.toBean(jsonStr, User.class);
                    if (currentUser == null || currentUser.getId() == null) {
                        throw new BusinessException(ErrorCode.NOT_LOGIN_ERROR);
                    }
                    return getLoginUserVO(currentUser);
                } catch (Exception e) {
                    throw new BusinessException(ErrorCode.NOT_LOGIN_ERROR);
                }
            }
        }

//        //若没查到 到header看看
//        String sessionId = request.getHeader(USER_Seession_ID);

        // 从redis中获取用户信息
//        String jsonStr = (String) redisTemplate.opsForValue().get(USER_LOGIN_STATE + sessionId);
//        try {
//            User currentUser = JSONUtil.toBean(jsonStr, User.class);
//            if (currentUser == null || currentUser.getId() == null) {
//                throw new BusinessException(ErrorCode.NOT_LOGIN_ERROR);
//            }
        // 从数据库查询（追求性能的话可以注释，直接走缓存）
//            long userId = currentUser.getId();
//            currentUser = this.getById(userId);
//            if (currentUser == null) {
//                throw new BusinessException(ErrorCode.NOT_LOGIN_ERROR);
//            }
        // 2. 基于ThreadLocal获取
        return null;
//    } catch(
//    Exception e)
//
//    {
//        throw new BusinessException(ErrorCode.NOT_LOGIN_ERROR);
//    }

    }


    @Override
    public LoginUserVO getLoginUserVO(User user) {
        if (user == null) {
            return null;
        }
        LoginUserVO loginUserVO = new LoginUserVO();
        BeanUtils.copyProperties(user, loginUserVO);
        return loginUserVO;
    }


}
